using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Text;
using System.Web;
using TST.SharePoint.Shared;

namespace TST.WebParts
{
	/// <summary>
	/// Description of the toolpart. Override the GetToolParts method in your Web Part
	/// class to invoke this toolpart. To establish a reference to the Web Part 
	/// the user has selected, use the ParentToolPane.SelectedWebPart property.
	/// </summary>
    public class ContentByTypeEditorPart : EditorBase
	{
        /// <summary>
        /// Gets or sets the configuration XML.
        /// </summary>
        /// <value>The field configuration.</value>
        private string CurrentConfiguration
        {
            get { return (string)ViewState["currentConfiguration"] ?? string.Empty; }
            set { ViewState["currentConfiguration"] = value; }
        }

        /// <summary>
        /// Constructor for the class. A great place to set Set default
        /// values for additional base class properties here.
        /// </summary>
        public ContentByTypeEditorPart(string webPartID)
        {
            this.ID = string.Format("ContentByTypeConfiguration{0}", webPartID);
            this.Title = "Configuration";
        }

        /// <summary>
        /// Gets the configuration xml from the webpart and
        /// puts it in the textcontrol for editing.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (CurrentConfiguration.Length == 0)
                CurrentConfiguration = (WebPart).Configuration;

            this.EnsureChildControls();
        }

        /// <summary>
        /// Create all controls on the toolpart.
        /// </summary>
        protected override void CreateChildControls()
        {
            // Descriptive text.	
            String linkText = String.Format("<a href=\"javascript:OpenConfigurationEditorDialog();\" alt=\"{0}\" title=\"{0}\">{1}</a>", "Open the Content By Type Configuration Editor", "Open the Configuration Editor");

            this.Controls.Add(new LiteralControl(String.Concat("<p>Use the Content By Type editor to configure your webpart. Open the configuration editor by clicking the link below.<br /></p><p>", linkText, ".</p>")));

            base.CreateChildControls();
        }

        protected override void OnPreRender(EventArgs e)
        {
            //Insert JScript on PreRender
            RegisterOpenScript();

            base.OnPreRender(e);
        }
        
        /// <summary>
        /// Registers the open script.
        /// </summary>
        protected void RegisterOpenScript()
        {
            if (WebPart == null)
                return;
            //string sScriptKey = "OpenScriptKey";
            string scriptKey = string.Format("OpenScriptKey_{0}", WebPart.ID);
           
            //The code below contatenates a string containing the JScript code
            //JScript code opens a dialog window using showModalDialog() and puts
            //the returnValue into a text input HTML element on the tool part page using the unique ID
            StringBuilder EmbeddedScriptFormat = new StringBuilder();
            EmbeddedScriptFormat.Append("function OpenConfigurationEditorDialog(){");
            EmbeddedScriptFormat.Append("var sReturnValue; ");
            EmbeddedScriptFormat.Append("sReturnValue = window.showModalDialog");
            EmbeddedScriptFormat.AppendFormat("(\"/_layouts/TST/ContentByTypeEditor.v13.aspx?pageUrl={0}&storageKey={1}&siteUrl={2}\"", 
                HttpUtility.UrlEncode(System.Web.HttpContext.Current.Request.Url.ToString()),
                this.WebPart.ID,
                HttpUtility.UrlEncode(SPContext.Current.Web.Url));
            EmbeddedScriptFormat.Append(",\"\",\"dialogWidth:840px; dialogHeight:840px;");
            EmbeddedScriptFormat.Append("status:no;help:no\");");
            EmbeddedScriptFormat.Append("}");

            //Check if the script is currently registered, and register if it is not
            if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptKey))
                Page.ClientScript.RegisterClientScriptBlock(typeof(ContentByTypeEditorPart), scriptKey, EmbeddedScriptFormat.ToString(), true);
        }

        ///	<summary>
        ///	Called by the tool pane to apply property changes to the
        ///	selected Web Part. 
        ///	</summary>
        public override bool ApplyChanges()
        {
            return true;
        }

        /// <summary>
        ///	If the ApplyChanges method succeeds, this method is called by the tool pane 
        ///	to refresh the specified property values in the toolpart user interface.
        /// </summary>
        public override void SyncChanges()
        {
            // sync with the new property changes here
        }

 	}											
}